//
//  CardViewController.swift
//  XMGWB
//
//  Created by 1 on 16/1/8.
//  Copyright © 2016年 xiaomage. All rights reserved.
//

import UIKit

class CardViewController: UIViewController {
    
    // MARK:- 属性
    @IBOutlet weak var qrcodeView: UIImageView!
    
    // MARK:- 系统回调的函数
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 1.创建滤镜
        let filter = CIFilter(name: "CIQRCodeGenerator")
        
        // 2.恢复默认设置
        filter?.setDefaults()
        
        // 3.设置数据
        let qrcodeInfo = "http://www.520it.com"
        guard let qrcodeInfoData = qrcodeInfo.dataUsingEncoding(NSUTF8StringEncoding) else {
            return
        }
        filter?.setValue(qrcodeInfoData, forKeyPath: "inputMessage")
        
        // 4.获取生产的图片
        guard let outputImage = filter?.outputImage else {
            return
        }
        
        // 5.设置图片
        let image = scaleImage(outputImage)
        
        // 6.在二维码中画上头像
        qrcodeView.image = drawIconView(image, iconName: "Avatar")
    }
    
    private func drawIconView(image : UIImage, iconName : String) -> UIImage {
        // 1.开启图片上下文
        UIGraphicsBeginImageContext(image.size)
        
        // 2.将图片画到上下文中
        image.drawInRect(CGRect(origin: CGPointZero, size: image.size))
        
        // 3.根据图标名称生成图片,并且将图片画到上下文中
        let iconImage = UIImage(named: iconName)
        let width : CGFloat = 60
        let height : CGFloat = 60
        let x = (image.size.width - width) * 0.5
        let y = (image.size.height - height) * 0.5
        iconImage?.drawInRect(CGRect(x: x, y: y, width: width, height: height))
        
        // 4.获取图片
        let drawImage = UIGraphicsGetImageFromCurrentImageContext()
        
        // 5.关闭上下文
        UIGraphicsEndImageContext()
        
        return drawImage
    }
    
    private func scaleImage(ciImage : CIImage) -> UIImage {
        // 1.创建放大的系数
        let tranform = CGAffineTransformMakeScale(10, 10)
        
        // 2.根据放大系数放大的图片
        let newImage = ciImage.imageByApplyingTransform(tranform)
        
        // 3.返回生成好的图片
        return UIImage(CIImage: newImage)
    }
}
